<template>
  <div
    ref="fanSpeedChart"
    class="charts"
    style="width: 100%; height: 200px"
  ></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { useI18n } from 'vue-i18n';

const i18n = reactive(useI18n());
const props = defineProps<{ fanSpeeds: Object }>();

const fanSpeedChart = ref();
const interval = ref();

const fanNameList = computed(() => Object.keys(props.fanSpeeds));
const fanSpeedList = computed(() => Object.values(props.fanSpeeds));

onBeforeUnmount(() => {
  clearInterval(interval.value);
});

onMounted(() => {
  var SpeedChart = echarts.init(fanSpeedChart.value);
  interval.value = setInterval(() => {
    SpeedChart.setOption({
      title: {
        subtext: i18n.t('pageFanSpeed.chart.title.subtext'),
      },
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        axisTick: { show: false },
        data: fanNameList.value,
        axisLabel: {
          textStyle: {
            fontSize: 12,
          },
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          show: true,
          interval: 'auto',
          formatter: '{value} RPM',
        },
        min: () => 0,
        max: () => 20000,
        show: true,
      },
      series: [
        {
          name: i18n.t('pageFanSpeed.chart.fanSpeed'),
          type: 'bar',
          data: fanSpeedList.value,
          itemStyle: {
            color: 'green',
          },
          label: {
            show: fanSpeedList.value[0] != 0 ? true : false,
            position: 'top',
            formatter: '{c} RPM',
          },
          barWidth: '0%',
        },
      ],
    });
  }, 2000);
});
</script>
